<?php

namespace Apps\AppApi\Method\Question;
use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\Question;
use Apps\Common\Models\QuestionFollow;
use Apps\Common\Models\QuestionViewsUser;
use PhalconPlus\Api\Common\ResultStatus;


/**
 * 问题详情
 * @package Apps\AppApi\Method\GetInfo
 */
class GetInfo extends BaseMethod
{
    public function run()
    {
        $id = intval($this->getDataItem('id',0));
        $user_id = intval($this->getDataItem('user_id', 0));

        if ($id == 0) {
            return $this->errorLog(ResultStatus::URL_PARAM_CANNOT_EMPTY, 'URL参数不全');
        }

        $Question = new Question();
        $model = $Question->query()->columns([
            'question_id',
            'question_content',
            'question_pics',
            'question_tag',
            'answer_num',
            'question_browsers',
            'question_addtime',
            'u.user_id',
            'u.user_nickname',
            'u.user_expert',
            'u.user_cover',
            'u.user_gender',
        ])->leftJoin('\Apps\Common\Models\UserBase', 'u.user_id = \Apps\Common\Models\Question.user_id', 'u')->where('question_state = 1 and question_id = ' . $id)->execute()->getFirst();

        if ($model) {
            $info = $model->toArray();

            $info['question_content'] = unserialize(base64_decode($info['question_content'])) ?: $info['question_content'];

            if ($info['question_pics']) {
                $question_pics = [];
                foreach (json_decode($info['question_pics'], true) as $val) {
                    $question_pics[] = PicUrl::Question($val, $this->getDi());
                }
                $info['question_pics'] = $question_pics;
            }
            $info['user_cover'] = PicUrl::UserCover($info['user_cover'], $this->getDi());
            $info['question_tag'] = $info['question_tag'] ? json_decode($info['question_tag'], true) : [];

            $QuestionFollow = new QuestionFollow();
            // 是否收藏过
            if ($user_id) {
                $info['is_collection'] = $QuestionFollow->is_follow($info['question_id'], $user_id);
            } else {
                $info['is_collection'] = '0';
            }

            $QuestionViewsUser = new QuestionViewsUser();
            $info['user_views_list'] = $QuestionViewsUser->getViewsUserList($id, 0, 7);

            $this->setResult($info);

            $count = 1;
            $Question->getReadConnection()->query("UPDATE question SET question_browsers = question_browsers + {$count} WHERE question_id = {$id}");

            if ($user_id) {
                $QuestionViewsUser->addData($id, $user_id);
            }
        }
    }

}